package org.lhg.activiti.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.ProcessDefinition;
import org.lhg.activiti.model.FormTable;
import org.lhg.activiti.model.MyProcessDefinition;
import org.lhg.activiti.model.PageBean;
import org.lhg.activiti.service.FormTableService;
import org.lhg.activiti.util.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.*;

@RestController
@RequestMapping("/formTable")
public class FormTableController {

    @Autowired
    private FormTableService formTableService;
    @Autowired
    private RepositoryService repositoryService;

    /**
     * 表单分页
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping(value = "/listFormTable",method = RequestMethod.GET)
    public CommonResult<JSONObject> listFormTable(@RequestParam(value="page",defaultValue="0")String page, @RequestParam(value="limit",defaultValue="0")String limit){
        PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(limit));
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("start", pageBean.getStart());
        map.put("size", pageBean.getPageSize());
        List<FormTable> tableList=formTableService.listFormTable(map);
        Long total=formTableService.getTotal(map);

        JSONObject result=new JSONObject();
        JSONArray jsonArray= JSONArray.parseArray(JSON.toJSONString(tableList));
        result.put("rows", jsonArray);
        result.put("total", total);
        return CommonResult.success(result);
    }

    /**
     * 新增表单
     * @param formTable
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addFormTable",method = RequestMethod.POST)
    public CommonResult<JSONObject> addFormTable(@RequestBody FormTable formTable) throws Exception {
        int resultTotal=0;
        formTable.setCreateTime(new Date());
        resultTotal=formTableService.addFormTable(formTable);
        JSONObject result=new JSONObject();
        if(resultTotal>0){
            result.put("success", true);
        }else{
            result.put("success", false);
        }
        return CommonResult.success(result);
    }

    /**
     * 上传表单文件
     * @param formFile
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public CommonResult<JSONObject> upload(@RequestParam("formFile") MultipartFile formFile, @RequestParam("id")String id, HttpServletResponse response)throws Exception{
        JSONObject result=new JSONObject();
        BufferedReader reader = null;
        StringBuilder ans = new StringBuilder();
        Reader read = new InputStreamReader(formFile.getInputStream(), "utf-8");
        reader = new BufferedReader(read);
        String tmpString = null;
        //一行一行的读取文件里面的内容
        while((tmpString = reader.readLine()) != null){
            ans.append(tmpString);//保存在ans里面
        }
        FormTable formTable=formTableService.findById(id);
        formTable.setFormContent(ans.toString());
        int resultTotal=formTableService.updateFormTable(formTable);
        if(resultTotal>0){
            result.put("success", true);
        }else{
            result.put("success", false);
        }
        return CommonResult.success(result);
    }

    @RequestMapping(value = "/processComboList")
    public CommonResult<JSONObject> processComboList(){
        JSONObject result=new JSONObject();
        List<ProcessDefinition> processDefinition=repositoryService.createProcessDefinitionQuery() // 创建流程流程定义查询
                .orderByProcessDefinitionId().desc() // 根据流程定义id降序排列
                .latestVersion()
                .list(); // 返回结果集合
        List< MyProcessDefinition> processList=new ArrayList<MyProcessDefinition>();

        for(ProcessDefinition p:processDefinition){
            MyProcessDefinition myProcessDefinition=new MyProcessDefinition();
            myProcessDefinition.setId(p.getId());
            myProcessDefinition.setName(p.getName());
            myProcessDefinition.setKey(p.getKey());
            myProcessDefinition.setVersion(p.getVersion());
            myProcessDefinition.setResourceName(p.getResourceName());
            myProcessDefinition.setDiagramResourceName(p.getDiagramResourceName());
            myProcessDefinition.setDeploymentId(p.getDeploymentId());
            processList.add(myProcessDefinition);
        }
        JSONArray jsonArray= JSONArray.parseArray(JSON.toJSONString(processList));
        result.put("rows",jsonArray);
        result.put("success",true);
        return CommonResult.success(result);
    }

    /**
     * 删除
     * @param map
     */
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public CommonResult<JSONObject>  delete(@RequestBody Map<String,Object>map)  {
        JSONObject result=new JSONObject();
        String id=map.get("id").toString();
        int resultTotal= formTableService.deleteByFormId(id);
        if(resultTotal>0){
            result.put("success", true);
        }else{
            result.put("success", false);
        }
        return CommonResult.success(result);
    }

    //写入html内容 覆盖原内容
    @RequestMapping(value = "/write_html_file",method = RequestMethod.POST)
    public CommonResult<JSONObject> write_html_file(@RequestBody Map<String,Object>map) {
        JSONObject result=new JSONObject();
        String processInstanceKey=map.get("processInstanceKey").toString();
        FormTable formTable=formTableService.formTable_by_processInstanceKey(processInstanceKey);
        result.put("formTable",formTable);
        result.put("success",true);
        return CommonResult.success(result);
    }

}
